const db = require('../db/index')



// 保存登录日志
exports.saveLoginLog = (req, res) => {
  const { account, name, email } = req.body
  const login_time = new Date()
  const sql = `insert into login_log set ?`
  db.query(sql, { account, name, email, login_time }, (err, results) => {
    if (err) return res.cc(err)
    if (results.affectedRows !== 1) return res.cc('保存失败')
    res.send({
      status: 0,
      message: '保存录日志成功'
    })
  })
}

// 获取登录日志
exports.getLoginLogList = (req, res) => {
  const sql = `select * from login_log`
  db.query(sql, (err, results) => {
    if (err) return res.cc(err)
    res.send({
      status: 0,
      message: '获取录日志成功',
      data: results
    })
  })
}

// 搜索最近十条日志
exports.getRecentTenLoginLog = (req, res) => {
  const sql = `select * from login_log where  account = ? order by login_time limit 10 `
  db.query(sql, req.body.account, (err, results) => {
    if (err) return res.cc(err)
    res.send({
      status: 0,
      message: '获取最近十条登录日志成功',
      data: results
    })
  })
}

// 获取登录总长度
exports.getLoginLogTotal = (req, res) => {
  const sql = `select count(*) as length from login_log`
  db.query(sql, (err, results) => {
    if (err) return res.cc(err)
    res.send({
      status: 0,
      message: '获取登录日志总长度成功',
      data: results[0]
    })
  })
}

// 根据页码换页  前端参数: pager
exports.getLoginLogByPager  = (req, res) => {
  const pager = (req.body.pager - 1) * 10
  const sql = `select * from login_log limit 10 offset ${pager}`
  db.query(sql, (err, result) => {
    if (err) return res.cc(err)
    res.send({
      status: 0,
      message: `获取第${pager + 1}登录日志分页成功`,
      data: result
    })
  })
}

// 清空所有登录日志
exports.clearLoginLogList = (req, res) => {
  const sql = `truncate table login_log`
  db.query(sql, (err, results) => {
    if (err) return res.cc(err)
    res.send({
      status: 0,
      message: '清空登录日志成功'
    })
  })
}